import './index.css'

import { Button, Col, Form, Input, Radio, Row, Space, message } from 'antd'
import React, { useEffect, useMemo, useState } from 'react'
import {
  checkSmsCode,
  checkUsername,
  getRole,
  register,
  sendUniSMS
} from '../../api'

import $axios from '../../sever'
import { useNavigate } from 'react-router-dom'

// import zxcvbn from 'zxcvbn'

// import type { RadioChangeEvent } from 'antd'
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 }
}

const tailLayout = {
  wrapperCol: { offset: 12, span: 16 }
}

const Register: React.FC = () => {
  const navigate = useNavigate()
  const [messageApi, contextHolder] = message.useMessage() //全局提示信息
  const [form] = Form.useForm()
  const [roleList, setRoleList] = useState([])
  const [phone, setphone] = useState('')
  const [flag, setflag] = useState(false)
  const [sendFlag, setSendFlag] = useState(false)
  const [password, setPassword] = useState('')

  // 密码强度计算
  const handlePassword = useMemo(() => {
    const score = zxcvbn(password).score
    if (score === 0 || score === 1) {
      return '弱'
    } else if (score === 2 || score === 3) {
      return '中'
    } else if (score === 4) {
      return '强'
    }
    // return score * 25
  }, [password])

  const handleGetRole = async () => {
    const { roleList } = await getRole()
    setRoleList(roleList)
    form.setFieldsValue({
      permissionsId: roleList[1]._id
    })
  }
  useEffect(() => {
    handleGetRole()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 注册
  const onFinish = async () => {
    const res = await register(form.getFieldsValue())
    if (res.code === 200) {
      navigate('/login')
    }
  }

  // 发送手机验证码
  const sendCode = async () => {
    const { code, msg } = await sendUniSMS(phone)
    if (code == 200) {
      setflag(true)
      messageApi.open({
        type: 'success',
        content: msg
      })
    } else {
      messageApi.open({
        type: 'error',
        content: msg
      })
    }
  }
  // 重置表单
  const onReset = () => {
    form.resetFields()
  }

  // 检测手机是否合法
  const checkPhone = async (_: any, value: string) => {
    const { code, msg } = await $axios.post('/users/check-phone', {
      phone: value
    })
    if (code === 201) {
      setSendFlag(false)
      return Promise.reject(msg)
    } else {
      setSendFlag(true)
    }

    const rep = /^1[3-9]\d{9}$/
    if (!rep.test(value)) {
      return Promise.reject('手机号不合法')
    }
    return Promise.resolve()
  }

  // 检查邮箱是否合法
  const checkEmail = (_: any, value: string) => {
    const rep = /^[1-9][0-9]{4,10}@qq\.com$/
    if (!rep.test(value)) {
      return Promise.reject('邮箱不合法')
    }
    return Promise.resolve()
  }

  // 检查密码
  const checkPwd = (_: any, value: string) => {
    if (value.length < 8 || value.length > 16) {
      return Promise.reject('密码长度8-16位')
    }
    const reg =
      /^(?=(?:.*[a-zA-Z]){1})(?=(?:.*[0-9]){1}|(?:.*[!@#$%^&*()_+\\\-={}[\]:;"'<>,.?\\/]){1}|(?:.*[!@#$%^&*()_+\\\-={}[\]:;"'<>,.?\\/]){1})(?:[a-zA-Z0-9!@#$%^&*()_+\\\-={}[\]:;"'<>,.?\\/]){8,16}$/

    if (!reg.test(value)) {
      return Promise.reject('密码必须包含数字、字母、特殊符号')
    }
    return Promise.resolve()
  }

  // 检查验证码长度
  const checkCode = async (_: any, value: string) => {
    if (value.length !== 6) {
      return Promise.reject('验证码长度为6位')
    }

    const { code } = await checkSmsCode(phone, value)
    if (code === 201) {
      return Promise.reject('验证码错误')
    }
    return Promise.resolve()
  }

  // 检查用户名
  const checkusername = async (_: any, value: string) => {
    if (value.length < 4 || value.length > 10) {
      return Promise.reject('用户名长度为4-10')
    }

    const { code, msg } = await checkUsername(value)
    if (code === 201) {
      return Promise.reject(msg)
    }
    return Promise.resolve()
  }

  return (
    <div>
      {contextHolder}
      <Form
        {...layout}
        form={form}
        name="control-hooks"
        onFinish={onFinish}
        style={{ maxWidth: 600 }}
      >
        <h1>注册</h1>
        {/* 用户名 */}
        <Form.Item
          validateFirst={true}
          name="username"
          label="用户名"
          rules={[{ required: true }, { validator: checkusername }]}
        >
          <Input />
        </Form.Item>
        {/* 密码 */}
        <Form.Item label="密码">
          <Row gutter={20}>
            <Col span={21}>
              <Form.Item
                validateFirst={true}
                name="password"
                noStyle
                rules={[{ required: true }, { validator: checkPwd }]}
              >
                <Input.Password
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
              </Form.Item>
            </Col>
            <Col span={3}>{password.length > 0 && <p>{handlePassword}</p>}</Col>
          </Row>
        </Form.Item>
        {/* 手机号 */}
        <Form.Item
          validateFirst={true}
          name="phone"
          label="手机号"
          rules={[{ required: true }, { validator: checkPhone }]}
        >
          <Input value={phone} onChange={(e) => setphone(e.target.value)} />
        </Form.Item>
        {/* 验证码 */}
        <Form.Item label="验证码">
          <Row gutter={20}>
            <Col span={17}>
              <Form.Item
                validateFirst={true}
                name="smscode"
                noStyle
                rules={[{ required: true }, { validator: checkCode }]}
              >
                <Input.OTP />
              </Form.Item>
            </Col>
            <Col span={7}>
              <Button disabled={!sendFlag || flag} onClick={sendCode}>
                发送验证码
              </Button>
            </Col>
          </Row>
        </Form.Item>
        {/* 邮箱 */}
        <Form.Item
          name="email"
          label="邮箱"
          rules={[{ required: true }, { validator: checkEmail }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          hidden
          name="permissionsId"
          label="角色"
          rules={[{ required: true }]}
        >
          <Radio.Group value={roleList[1]?._id}>
            <Radio value={roleList[1]?._id}>{roleList[1]?.RoleName}</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit">
              注册
            </Button>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  )
}
export default Register
